from models import Dataset, User
import timeseries

import os, sys

def autodetect ():
	""" Scans for new datasets not yet known about and adds them to the database. """
	data_path = sys.path[0] + "/econoplot/data/"
	files = [data_path + filename for filename in os.listdir (data_path) if filename[-4:] == ".ets"]
	messages = []
	for file in files:
		if Dataset.is_installed (file): continue
		ts = timeseries.get_info (file)
		dataset = Dataset ()
		# The s is for settings
		s = ts.__dict__
		if 'name' in s: dataset.name = ts.name
		if 'start' in s: dataset.start = ts.start
		if 'end' in s: dataset.end = ts.end
		if 'filename' in s: dataset.filename = ts.filename
		if 'created' in s: dataset.created = ts.created
		if 'x_units' in s: dataset.x_units = ts.x_units
		if 'y_units' in s: dataset.y_units = ts.y_units
		if 'source' in s: dataset.source = ts.source
		if 'source_url' in s: dataset.source_url = ts.source_url
		if 'source_article' in s: dataset.source_article = ts.source_article
		if 'source_section' in s: dataset.source_section = ts.source_section
		if 'source_table' in s: dataset.source_table = ts.source_table
		if 'data_mode' in s: dataset.data_mode = ts.data_mode
		if 'tags' in s: dataset.tags = ts.tags

		user = User.from_username (ts.author)
		if user: dataset.author = user		
		
		dataset.put ()
		messages.append ("Adding " + ts.name)
